import { Injectable, Logger, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { WorkflowTemplate, WorkflowTemplateDocument } from '../schemas/workflow.schema';
import { CreateWorkflowDto, UpdateWorkflowDto } from '../dto/workflow.dto';
import axios from 'axios';
import * as semver from 'semver';

@Injectable()
export class WorkflowManagementService {
    private readonly logger = new Logger(WorkflowManagementService.name);

    constructor(
        @InjectModel(WorkflowTemplate.name)
        private workflowModel: Model<WorkflowTemplateDocument>
    ) { }

    // 获取单个工作流
    async getWorkflow(id: string) {
        try {
            // 验证 ID 是否有效
            if (!id || id === 'undefined') {
                throw new BadRequestException('无效的工作流 ID');
            }
            // 如果是创建新工作流，直接返回
            if (id === 'create') {
                return null;
            }
            const workflow = await this.workflowModel.findById(id);
            if (!workflow) {
                throw new NotFoundException('工作流不存在');
            }
            return {
                success: true,
                data: workflow
            };
        } catch (error) {
            if (error instanceof BadRequestException) {
                throw error;
            }
            if (error instanceof NotFoundException) {
                throw error;
            }
            this.logger.error(`Failed to get workflow ${id}:`, error);
            throw new BadRequestException('获取工作流失败');
        }
    }

    // 获取所有工作流
    async getAllWorkflows() {
        try {
            const workflows = await this.workflowModel.find().sort({ updateTime: -1 }).exec();
            return {
                success: true,
                data: workflows,
                total: workflows.length
            };
        } catch (error) {
            this.logger.error('Failed to get workflows:', error);
            throw new BadRequestException('获取工作流列表失败');
        }
    }

    // 创建工作流
    async createWorkflow(workflowData: CreateWorkflowDto) {
        try {
            // 预处理数据
            const processedData = this.preprocessWorkflowData(workflowData);

            // 验证工作流数据
            if (!processedData.comfyuiJson) {
                throw new BadRequestException('ComfyUI 工作流配置不能为空');
            }

            // 尝试验证工作流配置
            if (!this.isValidComfyUIJson(processedData.comfyuiJson)) {
                this.logger.debug('提交的工作流配置:', processedData.comfyuiJson);
                throw new BadRequestException('ComfyUI 工作流配置格式无效，请检查配置结构');
            }

            // 其他验证
            await this.validateWorkflow(processedData);

            // 创建新工作流
            const workflow = new this.workflowModel({
                ...processedData,
                createTime: new Date(),
                updateTime: new Date()
            });

            const result = await workflow.save();
            return {
                success: true,
                data: result
            };
        } catch (error) {
            this.logger.error('Failed to create workflow:', error);
            if (error instanceof BadRequestException) {
                throw error;
            }
            // 提供更具体的错误信息
            if (error.name === 'ValidationError') {
                throw new BadRequestException(`数据验证失败: ${error.message}`);
            }
            throw new BadRequestException('创建工作流失败，请检查提交的数据格式');
        }
    }

    // 更新工作流
    async updateWorkflow(id: string, workflowData: UpdateWorkflowDto) {
        try {
            const result = await this.workflowModel.findByIdAndUpdate(
                id,
                {
                    ...workflowData,
                    updateTime: new Date()
                },
                { new: true }
            );
            if (!result) {
                throw new NotFoundException('工作流不存在');
            }
            return { data: result };
        } catch (error) {
            this.logger.error(`Failed to update workflow ${id}:`, error);
            throw new BadRequestException('更新工作流失败');
        }
    }

    // 删除工作流
    async deleteWorkflow(id: string) {
        try {
            const result = await this.workflowModel.findByIdAndDelete(id);
            if (!result) {
                throw new NotFoundException('工作流不存在');
            }
            return { success: true };
        } catch (error) {
            this.logger.error(`Failed to delete workflow ${id}:`, error);
            throw new BadRequestException('删除工作流失败');
        }
    }

    // 点赞工作流
    async likeWorkflow(id: string) {
        try {
            if (!id || id === 'undefined') {
                throw new BadRequestException('无效的工作流 ID');
            }

            // 验证 ID 格式
            if (!Types.ObjectId.isValid(id)) {
                throw new BadRequestException('无效的工作流 ID 格式');
            }

            const workflow = await this.workflowModel.findById(id);
            if (!workflow) {
                throw new NotFoundException('工作流不存在');
            }

            // 更新点赞数
            workflow.stats.likes += 1;
            await workflow.save();

            return {
                success: true,
                data: workflow
            };
        } catch (error) {
            this.logger.error(`Failed to like workflow ${id}:`, error);
            if (error instanceof BadRequestException || error instanceof NotFoundException) {
                throw error;
            }
            throw new BadRequestException('点赞失败');
        }
    }

    // 生成图片
    async generateImage(id: string, params: Record<string, any>) {
        try {
            const workflow = await this.workflowModel.findById(id);
            if (!workflow) {
                throw new NotFoundException('工作流不存在');
            }

            // TODO: 调用 ComfyUI API 生成图片
            // 这里暂时返回模拟数据
            const mockImage = 'https://example.com/generated-image.png';

            // 更新使用次数
            workflow.stats.uses += 1;
            await workflow.save();

            return { data: { image: mockImage } };
        } catch (error) {
            this.logger.error(`Failed to generate image for workflow ${id}:`, error);
            throw new BadRequestException('生成图片失败');
        }
    }

    async validateWorkflow(workflowData: CreateWorkflowDto) {
        // 验证名称唯一性
        const existingWorkflow = await this.workflowModel.findOne({ name: workflowData.name });
        if (existingWorkflow) {
            throw new BadRequestException('工作流名称已存在');
        }

        // 验证 ComfyUI JSON 格式
        if (!this.isValidComfyUIJson(workflowData.comfyuiJson)) {
            throw new BadRequestException('无效的 ComfyUI 工作流配置');
        }

        // 验证缩略图 URL
        if (!await this.isValidImageUrl(workflowData.thumbnail)) {
            throw new BadRequestException('无效的缩略图 URL');
        }

        return true;
    }

    async testWorkflow(id: string) {
        try {
            const workflow = await this.workflowModel.findById(id);
            if (!workflow) {
                throw new BadRequestException('工作流不存在');
            }

            // 测试工作流配置
            const testResult = await this.runWorkflowTest(workflow.comfyuiJson);
            return { success: true, result: testResult };
        } catch (error) {
            this.logger.error(`Failed to test workflow ${id}:`, error);
            throw new BadRequestException('工作流测试失败');
        }
    }

    private isValidComfyUIJson(json: Record<string, any>): boolean {
        try {
            // 基本结构验证
            if (!json || typeof json !== 'object') {
                this.logger.debug('ComfyUI JSON 不是有效的对象');
                return false;
            }

            // 如果是字符串，尝试解析
            if (typeof json === 'string') {
                try {
                    json = JSON.parse(json);
                } catch (error) {
                    this.logger.debug('ComfyUI JSON 字符串解析失败');
                    return false;
                }
            }

            // 最小化验证：只要是对象且包含基本结构即可
            const hasValidStructure = (
                // 检查是否有基本的工作流结构
                (json.nodes === undefined || typeof json.nodes === 'object' || Array.isArray(json.nodes)) &&
                (json.edges === undefined || typeof json.edges === 'object' || Array.isArray(json.edges)) &&
                // 允许其他可选字段
                typeof json === 'object'
            );

            if (!hasValidStructure) {
                this.logger.debug('ComfyUI JSON 缺少必要的结构', json);
                return false;
            }

            // 如果有节点，进行基本验证
            if (json.nodes) {
                const nodes = Array.isArray(json.nodes) ? json.nodes : Object.values(json.nodes);

                for (const node of nodes) {
                    if (!node || typeof node !== 'object') {
                        this.logger.debug('节点不是有效的对象', node);
                        continue; // 跳过无效节点，但不影响整体验证
                    }
                }
            }

            // 如果有连接，进行基本验证
            if (json.edges) {
                const edges = Array.isArray(json.edges) ? json.edges : Object.values(json.edges);

                for (const edge of edges) {
                    if (!edge || typeof edge !== 'object') {
                        this.logger.debug('连接不是有效的对象', edge);
                        continue; // 跳过无效连接，但不影响整体验证
                    }
                }
            }

            return true;
        } catch (error) {
            this.logger.error('ComfyUI JSON 验证失败:', error);
            return false;
        }
    }

    private async isValidImageUrl(url: string): Promise<boolean> {
        try {
            // 如果是 base64 图片数据
            if (url.startsWith('data:image/')) {
                return true;
            }

            // 如果是本地上传的图片
            if (url.startsWith('/uploads/')) {
                return true;
            }

            // 如果是远程图片，验证可访问性
            if (url.startsWith('http')) {
                const response = await axios.head(url);
                const contentType = response.headers['content-type'];
                return contentType.startsWith('image/');
            }

            return false;
        } catch (error) {
            this.logger.error('Image URL validation failed:', error);
            return false;
        }
    }

    private isValidVersion(version: string): boolean {
        return semver.valid(version) !== null;
    }

    private async runWorkflowTest(comfyuiJson: Record<string, any>) {
        try {
            // 这里实现工作流测试逻辑
            // 1. 验证工作流结构
            if (!this.isValidComfyUIJson(comfyuiJson)) {
                throw new BadRequestException('无效的工作流配置');
            }

            // 2. 执行简单的工作流测试
            const testResult = await this.executeTestWorkflow(comfyuiJson);
            return testResult;
        } catch (error) {
            this.logger.error('Workflow test failed:', error);
            throw new BadRequestException('工作流测试失败');
        }
    }

    private async executeTestWorkflow(comfyuiJson: Record<string, any>) {
        // 这里实现具体的工作流执行测试逻辑
        // 可以调用 ComfyUI API 进行实际测试
        // 暂时返回模拟数据
        return {
            status: 'success',
            executionTime: 1000,
            nodeCount: comfyuiJson.nodes.length,
            memoryUsage: '128MB'
        };
    }

    // 添加工作流数据预处理方法
    private preprocessWorkflowData(data: CreateWorkflowDto): CreateWorkflowDto {
        try {
            // 深拷贝数据以避免修改原始对象
            const processedData = JSON.parse(JSON.stringify(data));

            // 设置默认值
            processedData.author = processedData.author || 'anonymous';
            processedData.version = processedData.version || '1.0.0';
            processedData.isPublic = processedData.isPublic ?? false;

            // 确保 comfyuiJson 是对象
            if (typeof processedData.comfyuiJson === 'string') {
                try {
                    processedData.comfyuiJson = JSON.parse(processedData.comfyuiJson);
                } catch (error) {
                    this.logger.debug('ComfyUI JSON 字符串解析失败:', error);
                    throw new BadRequestException('ComfyUI 工作流配置不是有效的 JSON 格式');
                }
            }

            // 规范化 comfyuiJson
            if (processedData.comfyuiJson) {
                processedData.comfyuiJson = {
                    nodes: processedData.comfyuiJson.nodes || {},
                    edges: processedData.comfyuiJson.edges || [],
                    ...processedData.comfyuiJson
                };
            }

            // 确保 tags 是数组
            if (!Array.isArray(processedData.tags)) {
                processedData.tags = processedData.tags ? [processedData.tags] : [];
            }

            // 过滤空标签
            processedData.tags = processedData.tags.filter(tag => tag && typeof tag === 'string');

            // 初始化统计信息
            processedData.stats = {
                uses: 0,
                likes: 0,
                views: 0,
                ...processedData.stats
            };

            return processedData;
        } catch (error) {
            this.logger.error('数据预处理失败:', error);
            throw new BadRequestException('数据预处理失败: ' + error.message);
        }
    }

    // 执行工作流
    async executeWorkflow(id: string, params: Record<string, any>) {
        try {
            if (!id || id === 'undefined') {
                throw new BadRequestException('无效的工作流 ID');
            }

            // 验证 ID 格式
            if (!Types.ObjectId.isValid(id)) {
                throw new BadRequestException('无效的工作流 ID 格式');
            }

            const workflow = await this.workflowModel.findById(id);
            if (!workflow) {
                throw new NotFoundException('工作流不存在');
            }

            // TODO: 实现工作流执行逻辑
            return {
                success: true,
                data: {
                    imageUrl: 'https://example.com/generated-image.png'
                }
            };
        } catch (error) {
            this.logger.error(`Failed to execute workflow ${id}:`, error);
            if (error instanceof BadRequestException || error instanceof NotFoundException) {
                throw error;
            }
            throw new BadRequestException('执行失败');
        }
    }

    // ... 其他辅助方法
}